import {
  ui
} from '~/tools/ui'
import {
  ds
} from '~/tools/data'
import {
  checkTool
} from '~/tools/check'
import {
  exTool
} from './exTool'
import {
  rsa
} from '~/tools/rsa'

Page({
  data: {
    pickingTime: false,
    values: {},
    action: 'generate',
    ticket: {}
  },
  onLoad(options) {
    const data = JSON.parse(options.data)
    const ticketLeft = data.ticketInfo.totalAmount - data.ticketInfo.used
    // console.log(data)
    this.setData({
      ...data,
      ticketLeft
    })
  },
  async onShow() {
    const {
      action,
      ticketIds
    } = this.data
    // console.log(this.data)
    if (action == 'exchange') {
      const orderRes = ds.coll('orders')
        .where({
          _id: ds.cmd.in(JSON.parse(ticketIds))
        })
        .get()
      const tickets = (await orderRes).data
      // console.log(tickets)
      this.setData({
        tickets
      })
    }
  },
  changeGiveawayNumTap(e) {
    this.setData({
      giveawayNum: e.detail.value
    })
  },
  exchangeTap(e) {
    const {
      ticket
    } = e.currentTarget.dataset
    // console.log(ticket)
    exTool.useTicket(ticket)
      .then(res => {
        this.onShow()
      })
  },
  async generateTap() {
    const {
      id,
      openid,
      user,
      ticketInfo,
      giveawayNum
    } = this.data
    if (!user?._id) return ui.toast(false, '未指定用户')

    ui.confirmx('确定赠予吗？').then(res => {
      if (!res) return

      ui.loading()
      ds.cloudUpdate('orders', id, {
        _openid: user._openid
      }, res => {
        // console.log(res)
        ui.loading(false)
        const success = res.result.errMsg.endsWith(":ok")
        ui.toast(success, '', () => {
          wx.navigateBack({
            delta: 3
          })
        })
      })
    })
  },
  checkValues(values) {
    checkTool.check([{
      value: values.allowType,
      title: '允许用户',
      fn: v => {
        if (v == '指定用户') return values.userList?.length > 0
        return v
      },
    }, {
      value: values.exOrder,
      title: '优先兑换'
    }, {
      value: '',
      title: '有效期',
      fn: () => {
        if (!values.start && !values.end) return true
        if (values.start && values.end) return values.start <= values.end
        return false
      }
    }])
  },
  onAllowTypeTap() {
    const that = this
    wx.scanCode({
      scanType: ['qrCode'],
      success: async (res) => {
        const success = res.errMsg.endsWith(":ok")
        ui.toast(success, '扫描成功')
        if (!success) return

        const {
          title,
          ex
        } = JSON.parse(res.result)
        if (title != '我的用户码') return ui.toast(false, '错误的用户码')
        // console.log(title, JSON.parse(rsa.decrypt(ex)))
        const {
          userId
        } = JSON.parse(rsa.decrypt(ex)) || {}
        const user = await that.loadUser(userId)
        if (!user) return ui.toast(false, '未找到用户')
        that.setData({
          user
        })
      },
      fail: (res) => {
        console.error(res)
      },
    });
  },
  // 优先兑换
  onExOrderTap() {

  },
  onStartTimeChange(e) {
    const {
      values
    } = this.data
    const {
      txt,
      timestamp
    } = e.detail
    values.start = timestamp
    this.setData({
      values
    })
  },
  onEndTimeChange(e) {
    const {
      values
    } = this.data
    const {
      txt,
      timestamp
    } = e.detail
    values.end = timestamp
    this.setData({
      values
    })
  },
  onStartTimeCancel() {
    const {
      values
    } = this.data
    values.start = ""
    this.setData({
      values
    })
  },
  onEndTimeCancel() {
    const {
      values
    } = this.data
    values.end = ""
    this.setData({
      values
    })
  },
  selectUserTap() {
    const {
      values
    } = this.data
    const userList = values.userList || []
    const end = (success, msg) => {
      ui.loading(false);
      if (msg) ui.toast(success, msg)
    }
    const that = this
    wx.scanCode({
      onlyFromCamera: true, // 只允许从相机扫码
      async success(res) {
        ui.loading()
        const {
          title,
          ex
        } = JSON.parse(res.result)
        if (title != '我的用户码') return end(false, '错误的用户码')
        // console.log(title, JSON.parse(rsa.decrypt(ex)))
        const {
          userId
        } = JSON.parse(rsa.decrypt(ex)) || {}
        const user = await that.loadUser(userId)
        if (!user) return end(false, '未找到用户')
        if (userList.find(ele => ele.id == userId)) return end(false, '该用户已在允许列表中')
        userList.push({
          id: userId,
          nickName: user.personInfo?.nickName || '(未命名用户)'
        })
        values.userList = userList
        that.setData({
          values
        })
        return end('true')
      },
    })

  },
  loadUser(userId) {
    return new Promise((resolve) => {
      ds.coll('users')
        .where({
          _id: ds.cmd.eq(userId)
        })
        .get()
        .then(res => {
          // console.log(res)
          resolve(res.data[0])
        })
    })
  },
  delUserTap(e) {
    const {
      index
    } = e.currentTarget.dataset
    // console.log(e)
    ui.confirm('确认删除吗？', confirm => {
      if (!confirm) return
      const {
        values
      } = this.data
      const userList = values.userList
      userList.splice(index, 1)
      values.userList = userList
      this.setData({
        values
      })
    })
  },
  onVisibleChange(e) {
    const {
      visible
    } = e.detail
    this.setData({
      pickingTime: visible
    })
  },
  end(success, msg) {
    ui.loading(false)
    if (msg) ui.toast(success, msg)
  }
})